<?php

namespace App\Models\Admin;

use App\Tools\Financial;
use App\Tools\Prstatic;

use Illuminate\Database\Eloquent\Model;

class GoodsRepertoryLog extends Model
{

    protected $table = 'goods_repertory_log';
    protected $primaryKey = 'id';
    protected $dateFormat = 'U';
    public $timestamps = false;
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s'
    ];

    protected $fillable = [
        'order_sn'
    ];

    /**
     * 获取列表
     */
    public static function getPageList($where = [], $limit = 15)
    {
        $data = [];
        if ($where['store_id']) {
            $data[] = ['s.id', '=', $where['store_id']];
        }
        if ($where['name']) {
            $data[] = ['g.goods_name', 'like', "%{$where['name']}%"];
        }
        if ($where['type']) {
            $data[] = ['r.type', '=', $where['type']];
        }
        if ($where['order_sn']) {
            $data[] = ['r.order_sn', '=', $where['order_sn']];
        }
        $start = $where['start_time'] ? strtotime($where['start_time']) : 0;
        $end = $where['end_time'] ? strtotime($where['end_time']) : time();
        $db = self::from('goods_repertory_log as r')
            ->select(['r.*', 'g.goods_sn', 'g.goods_name', 'g.goods_img', 'c.cate_name', 's.store_name'])
            ->leftJoin('goods as g', 'g.id', '=', 'r.goods_id')
            ->leftJoin('goods_category as c', 'c.id', '=', 'g.cate_id')
            ->leftJoin('store as s', 's.id', '=', 'r.store_id')
            ->where($data)
            ->whereBetween('r.created_at', [$start, $end])->orderBy('r.id', 'desc');
        if ($limit == 0) {
            $list = $db->get();
        } else {
            $list = $db->paginate($limit);
        }
        foreach ($list as $key => $vv) {
            $list[$key]['type_name'] = Prstatic::$stockType[$vv['type']];
        }
        return $list;
    }

    /**
     * 添加库存变动日志
     * @param $order_id
     * @param $goods_id
     * @param $goods_num
     * @param int $store_id
     * @param int $type
     * @param string $create_user
     * @return bool
     */
    public static function addInfoByGoodsId($order_id, $goods_id, $goods_num, $store_id = 0, $type = 1, $create_user = '', $orderSn = '', $money = 0)
    {
        $goods = Goods::where(['id' => $goods_id])->select(['goods_total_num', 'goods_sale_num'])->first();
        if ($goods) {
            if ($type == 1) {
                // 出库 减去库存
                $goods_after_num = $goods['goods_total_num'] - $goods_num;
                $goods_sale_num = $goods['goods_total_num'] - $goods_num;
                Goods::where(['id' => $goods_id])->update(['goods_total_num' => ($goods_sale_num), 'goods_sale_num' => ($goods['goods_sale_num'] - $goods_num)]);
                if ($store_id) {
                    // 商户加上库存
                    StoreGoods::upGoodsNumByOid($store_id, $goods_id, $goods_num, $create_user, $order_id, $money);
                }
            } elseif ($type == 2) {
                // 入库 加上库存
                $goods_after_num = $goods['goods_total_num'] + $goods_num;
                $goods_sale_num = $goods['goods_total_num'] + $goods_num;
                Goods::where(['id' => $goods_id])->update(['goods_total_num' => ($goods_sale_num), 'goods_sale_num' => ($goods['goods_sale_num'] + $goods_num)]);
            }
            //写入库存同步队列
            self::syncStockToWdt($goods->id, $goods_sale_num, time());
            $info['store_id'] = $store_id;
            $info['order_id'] = $order_id;
            $info['goods_id'] = $goods_id;
            $info['goods_num'] = $goods_num;
            $info['goods_after_num'] = $goods_after_num;
            $info['type'] = $type;
            $info['created_at'] = time();
            $info['create_user'] = $create_user;
            $info['order_sn'] = $orderSn;
            $info['goods_money'] = $money;
            return self::insert(array_filter($info));
        }
        return true;
    }
    /**
     * 推送库存同步数据到旺店通
     * @param int $rec_id
     * @param int $sync_stock
     * @param int $stock_change_count
     */
    public function syncStockToWdt($rec_id, $sync_stock, $stock_change_count)
    {
        $data = [
            [
                'rec_id' => $rec_id,
                'sync_stock' => $sync_stock,
                'stock_change_count' => $stock_change_count,
            ]
        ];

        $sid = config('services.wdt.sid');
        $appkey = config('services.wdt.appkey');
        $secret = config('services.wdt.secret');
        $url = config('services.wdt.url') . 'api_goods_stock_change_ack.php';

        $c = new \App\Console\Commands\WdtClient($sid, $appkey, $secret, $url);
        $c->putApiParam('stock_sync_list', json_encode($data, JSON_UNESCAPED_UNICODE));
        $result = $c->wdtOpenApi();

        \Log::info('实时同步库存到旺店通', ['data' => $data, 'result' => $result]);
        return $result;
    }
    /*
    * @param $param
    * @param int $limit
    * @return mixed
    */
    public static function getList($param, $limit = 15)
    {
        $where = array();
        if (isset($param['type']) && (int)$param['type'] > 0) {
            $where[] = ['grl.type', '=', (int)$param['type']];
        }
        if (isset($param['start']) && !empty($param['start'])) {
            $where[] = ['grl.created_at', '>', strtotime($param['start'])];
        }
        if (isset($param['end']) && !empty($param['end'])) {
            $where[] = ['grl.created_at', '<', strtotime($param['end'])];
        }
        if (isset($param['goods_name']) && !empty($param['goods_name'])) {
            $where[] = ['g.goods_name', 'like', "%" . trim($param['goods_name']) . "%"];
        }

        $sql = self::from('goods_repertory_log as grl')->where($where);
        if (isset($param['goods_ids']) && !empty($param['goods_ids'])) {
            $goodsIds = explode(',', $param['goods_ids']);
            $sql->whereIn('g.id', $goodsIds);
        }
        $list = $sql->select(['grl.*', 'g.goods_sn', 'g.goods_name', 'g.goods_price as old_price', 's.store_name'])
            ->leftJoin('goods as g', 'g.id', '=', 'grl.goods_id')
            ->leftJoin('store as s', 's.id', '=', 'grl.store_id')
            ->orderBy('grl.id', 'desc')
            ->paginate($limit);

        return $list;
    }

    /**
     * 获取所有列表
     * @param $param
     * @return mixed
     */
    public static function getAll($param)
    {
        $where = array();
        if (isset($param['goods_id']) && !empty($param['goods_id'])) {
            $where[] = ['goods_id', '=', (int)$param['goods_id']];
        }
        if (isset($param['start']) && !empty($param['start'])) {
            $where[] = ['created_at', '>', strtotime($param['start'])];
        }
        if (isset($param['end']) && !empty($param['end'])) {
            $where[] = ['created_at', '<', strtotime($param['end'])];
        }
        $list = self::where($where)->orderBy('id', 'asc')->get()->toArray();
        return $list;
    }

    /**
     * 获取最后一条记录
     * @param $param
     * @return mixed
     */
    public static function getLast($param)
    {
        $where = array();
        if (isset($param['goods_id']) && !empty($param['goods_id'])) {
            $where[] = ['goods_id', '=', (int)$param['goods_id']];
        }

        $list = self::where($where)->orderBy('id', 'desc')->first();
        return $list;
    }
}